<!-- 上传组件 支持分片上传-->
<template>
  <div
    v-loading="uploading"
    class="chunkUpload"
    :element-loading-text="loadingText"
    element-loading-spinner="el-icon-loading"
  >
    <el-upload
      ref="uploadChunk"
      class="upload-block"
      name="file"
      action="111"
      :show-file-list="true"
      :before-upload="beforeExcelUpload"
      :http-request="handleUploadRequest"
      :data="uploadData"
    >
      <!--      <div class="el-upload__text">-->
      <!--        {{uploadText}}-->
      <!--      </div>-->
      <!-- <i class="el-icon-upload" /> -->
      <el-button type="primary" size="mini" class="el-upload__text">
        大文件上传
      </el-button>
    </el-upload>
    <!-- <div v-for="(item,index) in fileLists" :key="index">
      <i class="el-icon-document" />
      <span>{{ item.name }}</span>
    </div> -->
  </div>
</template>

<script>
import { uploadByPieces } from './aetheruploadNew'
import compressImg from '@/utils/compressImg'

export default {
  name: 'UploadZip',
  props: ['uploadText', 'dialogShow'],
  data() {
    return {
      uploading: false,
      loadingText: '上传进度',
      fileList: [],
      fileLists: [],
      uploadPreview: '',
      percentage: 0,
      uploadData: { reduce_img: '' }
    }
  },
  computed: {},
  watch: {
    fileList(fileList) {
      this.fileLists.push(fileList[0])
      this.$nextTick(() => {
        this.dealUpload()
      })
    },
    dialogShow(val, value) {
      console.log(this.$refs.uploadChunk.uploadFiles)
      if (!val) {
        this.fileLists = []
        this.$refs.uploadChunk.uploadFiles = []
      }
    }
  },
  created() {},
  methods: {
    // 上传前
    async beforeExcelUpload(file) {
      this.fileList = []
      const url = await compressImg(file, 0.2)
      this.uploadData.reduce_img = url.file
      this.uploadPreview = URL.createObjectURL(file)
    },
    // 上传请求
    handleUploadRequest(back) {
      this.fileList.push(back.file)
    },
    // 处理上传文件
    dealUpload() {
      this.uploading = true
      uploadByPieces({
        files: this.fileList,
        chunkUrl:
          this.$store.getters.updateURL + 'attachment/sliceUploadAndSave',
        preUrl: this.$store.getters.updateURL + 'attachment/sliceUploadAndSave',
        progress: num => {
          this.loadingText = this.$t('上传进度') + num + '%'
          this.percentage = num
        },
        success: data => {
          this.loadingText = data
          this.uploading = false
          this.loadingText = this.$t('上传进度')
          // this.$emit('uploaded', data)
          // this.$emit('preview', this.uploadPreview)
        },
        error: err => {
          this.loadingText = this.$t('上传失败')
          this.uploading = false
          console.log(err)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.upload-block {
  width: 300px;
}
.chunkUpload {
  width: 360px;
}
</style>
